/*******************************************************************************
 *    系统名称   ：GMAgent服务系统
 *    公司      ： 成都欢娱乐互动
 *    文件名    ： AMF3Encoder.java
 *              (C) Copyright joyct Corporation 2011
 *               All Rights Reserved.
 * *****************************************************************************
 *    注意： 本内容仅限于 成都欢娱乐互动公司内部使用，禁止转发
 ******************************************************************************/
package com.ricky.core.net.protocol;

import java.nio.ByteOrder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.ricky.core.net.ByteBuffer;
import com.ricky.core.net.protocol.FlashPolicyMsg;
import com.ricky.core.net.msg.ByteContext;
import com.ricky.core.net.msg.Context;

/***
 *	AMF3Encoder.java</br>
 *	@author pu
 *  @Data 2011-11-1</br>
 *	@version v0.1</br>
 *	@Discription 
 ***/
public class AMF3Encoder extends ProtocolEncoderAdapter {

	/* (non-Javadoc)
	 * @see org.apache.mina.filter.codec.ProtocolEncoder#encode(org.apache.mina.core.session.IoSession, java.lang.Object, org.apache.mina.filter.codec.ProtocolEncoderOutput)
	 */
	@Override
	public void encode(IoSession session, Object in, ProtocolEncoderOutput out)
			throws Exception {
		
		if(in instanceof ByteContext)
		{
			
			byte[] reps = FlashPolicyMsg.allow_all.getBytes("UTF-8");
			IoBuffer buffer = IoBuffer.allocate(reps.length + 1);
			buffer.order(ByteOrder.BIG_ENDIAN);
			buffer.put(reps);
			buffer.put((byte) 0x0);
			buffer.flip();
			out.write(buffer);
			
//			ByteContext context=(ByteContext)in;		
//			byte[] bytes = context.getBytes();	
//			IoBuffer buf = IoBuffer.allocate(bytes.length, false);
//			buf.order(ByteOrder.BIG_ENDIAN);	
//			buf.setAutoExpand(true);		
//			buf.put(bytes);//类容
//			buf.flip();
//			out.write(buf);
		}else
		{
			Context<?> context=(Context<?>)in;		
			byte[] bytes = context.getBytes();	
			int len=bytes.length;
			IoBuffer buf = IoBuffer.allocate(bytes.length, false);
			buf.order(ByteOrder.BIG_ENDIAN);	
			buf.setAutoExpand(true);		
			buf.putInt(len);//长度
			buf.put(bytes);//类容
			buf.flip();
			out.write(buf);
		}
	}

}
